<template>
  <div class="answer-container">
    <!-- 答题卡上面的所有题型 -->
    <div class="topic-box" v-for="t in topicSheetIterator" :key="t.topicKey">
      <div class="title">{{ t.topicType }}</div>
      <div class="squares">
        <topic-square
          v-for="item in topics[t.topicKey]"
          :key="item.id"
          :order="item.order"
          :tid="item.id"
          :choice="answerSheet[item.order - 1]"
          :isWatching="item.order - 1 === watchIndex ? true : false"
          :scrollByIndex="scrollByIndex"
          :changeWatchingIndex="changeWatchingIndex"
        />
      </div>
    </div>
    <div class="tool">
      <el-button @click="submit" :disabled="!isCanBeSubmit" type="success" round
        >提交</el-button
      >
      <el-button
        :disabled="!isCanBeSubmit"
        @click="temporarySave"
        type="success"
        round
        >暂存</el-button
      >
    </div>
  </div>
</template>

<script>
/**
 * 需要完成的功能
 * 点击square就可以跳转到对应的题目
 * 滑动题目，squre对应高亮
 * 由同一个接口结果进行渲染
 * 点击提交后做校验，满足条件就可以提交
 */
import TopicSquare from "./TopicSquare.vue";
import { Message } from "element-ui";
import { uploadTestResult, uploadExamResult } from "@/services/student";
import { mapState } from "vuex";
export default {
  props: [
    "answerSheet",
    "topics",
    "watchIndex",
    "floorHeight",
    "scrollByIndex",
    "changeWatchingIndex",
    "isCanBeSubmit",
  ],
  components: { TopicSquare },
  name: "TopicSheet",
  methods: {
    submit() {
      // TODO:这里应该也有两种可能，一种是测试一种是考试，所以可能需要一个if去隔开

      const { exam_id } = this.$route.query;
      const { student_id } = JSON.parse(localStorage.getItem("userInfo"));
      const getSubjectTopicStartIndex = () => {
        if (
          this.topics.essayQuestion.length === 0 &&
          this.topics.blankQuestion.length === 0
        ) {
          return -1;
        } else {
          const stack = [];
          const sl = this.topics.singleChoice.length;
          const ml = this.topics.multipleChoice.length;
          const tofl = this.topics.trueOrFalse.length;
          // const bl = this.topics.blankQuestion.length;

          if (sl > 0) {
            stack.push(this.topics.singleChoice[sl - 1].order * 1);
          }
          if (ml > 0) {
            stack.push(this.topics.multipleChoice[ml - 1].order * 1);
          }
          if (tofl > 0) {
            stack.push(this.topics.trueOrFalse[tofl - 1].order * 1);
          }
          return stack.pop();
        }
      };
      const subjectTopicStartIndex = getSubjectTopicStartIndex();
      // 如果有exam_id，说明是考试
      if (exam_id) {
        uploadExamResult(
          exam_id,
          student_id,
          this.answerSheet,
          subjectTopicStartIndex
        ).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: "提交成功",
            });
            // 清除本地缓存
            const oldData = JSON.parse(
              localStorage.getItem("exerciseAnswerArr")
            );
            const newData = oldData.filter((v) => v.exam_id !== exam_id);
            localStorage.setItem("exerciseAnswerArr", JSON.stringify(newData));
            // TODO:
            // 重新加载数据
            // 重新请求study
          } else {
            Message.error("提交失败，已为您保存数据");
            this.temporarySave();
          }
        });
      } else {
        // 说明是测试
        // uploadStudyResult()
        // 是否应该在这里提交呢？不一定吧，应该是在那个study被销毁的时候进行提交，那这里的提交是在做什么呢？
        /**
         * 单纯提交测试题的答案吗，或者是
         */
        const { course_id, section_id } = this;

        uploadTestResult(
          course_id,
          section_id,
          student_id,
          this.answerSheet,
          subjectTopicStartIndex
        ).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: "提交成功",
            });
            // 清除本地缓存
            const oldData = JSON.parse(
              localStorage.getItem("exerciseAnswerArr")
            );
            const newData = oldData.filter((v) => v.exam_id !== exam_id);
            localStorage.setItem("exerciseAnswerArr", JSON.stringify(newData));
          } else {
            Message.error("提交失败，已尝试为您保存数据");
            this.temporarySave();
          }
        });
      }
    },
    temporarySave() {
      /**
       * 暂存的逻辑：
       *  1.原本localStorage里面啥都没有=>先创建那个key然后加入那个value
       *  2.localStorage有exerciseAnswerArr但是没有那个exam_id对应的
       *  3.有那个exam_id对应的。
       */
      let { exam_id } = this.$route.query;
      // TODO: 这个地方如果是考试那么确实有exam_id，但是如果是单元测试，就没有exam_id了，只有course_id和section_id
      // console.log(exam_id);
      // 如果是考试
      if (!exam_id) {
        exam_id = this.course_id + "_" + this.section_id;
      }
      const saveData = {
        exam_id,
        answerSheet: this.answerSheet,
      };
      const oldData = JSON.parse(localStorage.getItem("exerciseAnswerArr"));
      if (oldData) {
        //如果oldData存在
        let flag = false;
        oldData.map((v) => {
          if (v.exam_id === exam_id) {
            // 更新topicAnswer
            v.answerSheet = this.answerSheet;
            flag = true;
          }
        });
        if (!flag) {
          oldData.push(saveData);
        }
        localStorage.setItem("exerciseAnswerArr", JSON.stringify(oldData));
      } else {
        // console.log([saveData])
        localStorage.setItem("exerciseAnswerArr", JSON.stringify([saveData]));
      }
      Message.success("保存成功！");
    },
  },
  computed: {
    ...mapState("studyAbout", {
      course_id: (state) => state.course.course_id,
      section_id: (state) => state.currentSection.id,
    }),
    topicSheetIterator() {
      return [
        {
          topicType: "单选题",
          topicKey: "singleChoice",
        },
        {
          topicType: "多选题",
          topicKey: "multipleChoice",
        },
        {
          topicType: "判断题",
          topicKey: "trueOrFalse",
        },
        {
          topicType: "填空题",
          topicKey: "blank",
        },
        {
          topicType: "问答题",
          topicKey: "essay",
        },
      ];
    },
  },
  // mounted() {
  //   this.course_id = localStorage.getItem("course_id");
  //   this.section_id = localStorage.getItem("section_id");
  // },
};
</script>

<style lang='less' scoped>
.answer-container {
  min-height: 240px;
  max-height: 500px;
  width: 280px;
  background-color: #fff;
  border-radius: 8px;
  position: fixed;
  top: 100px;
  right: 50px;
  box-shadow: 0px 2px 10px 0px rgb(237 238 240 / 50%);
  overflow: auto;
  padding: 20px 2px 0px 20px;
  .title {
    margin-bottom: 20px;
  }
  .squares {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    :deep(.topic-box) {
      margin-right: 16px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
      &:nth-child(5n + 1) {
        margin-left: 18px;
      }
    }
  }
  .tool {
    display: flex;
    // position: absolute;
    // bottom: 0;
    margin-bottom: 10px;
    justify-content: center;
    align-items: center;
  }
}
</style>